package com.jz.netthings.analysis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.analysis.bean.link.LinkAnalysisProviderSupport;
import com.jz.netthings.analysis.mapper.XyDevelopAnalysisMapper;
import com.jz.netthings.analysis.service.XyDevelopAnalysisService;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.bloodsources.mapper.XyLinkMapper;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.support.AdscmPage;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class XyDevelopAnalysisServiceImpl implements XyDevelopAnalysisService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    XyDevelopAnalysisMapper xyDevelopAnalysisMapper;

    @Autowired
    ProviderCollectionMapper providerCollectionMapper;

    @Autowired
    RedisTemplate<Object , Object> objectRedisTemplate;

    @Autowired
    XyLinkMapper xyLinkMapper;

    /**
     * 每天第一次查询浆量同期比的缓存，后面查询就查询缓存
     */
    private Map<String ,Map<String, Object>> pulpWeightMapCache = new HashMap<>();

    @Override
    public Map<String, Object> selectCollStatisticsByYear(Integer year) throws AdscmSystemException {

        logger.info("查询某一年的采浆量统计表：某年根据月、轮次、天，统计采浆量...");

        Map<String, Object> map = new HashMap<>();

        String beginTime = null;
        String endTime = null;
        if(year != null && year >0){
        }else {
            year = AdscmDateUtils.getTheYear(new Date());
        }
        beginTime = year + "-01-01 00:00:00";
        endTime = year + "-12-31 23:59:59";

        //查询每月的采浆总量
        List<Map<String,String>> monthCollCountList = xyDevelopAnalysisMapper.getMonthCollCount((year - 1) + "-12-31",year + "-12-31", beginTime, endTime);

        map.put("monthCollCount",monthCollCountList);

        //查询一年的采浆量统计
        String beginTime1 = (year - 1) + "-12-31";
        endTime = (year + 1) + "-01-01";
        List<Map<String, String>> dayCollCount = xyDevelopAnalysisMapper.getDayCollCount(beginTime1, beginTime, endTime);
        if (dayCollCount != null && dayCollCount.size()>0){
            int round = 1;
            int i = 1;
            int roundCount = 0;
            Map<String, Object> roundMap = new HashMap<>();
            Map<String, Object> dayMap = null;
            Map<String, Object> dataMap = null;
            for (Map<String, String> dcMap : dayCollCount) {

                if (i == 1){
                    dayMap = new HashMap<>();
                    dataMap = new HashMap<>();
                }
                String allCount = dcMap.get("collCount");
                try{
                    roundCount += Integer.parseInt(allCount);
                }catch (Exception e){}
                dayMap.put("day"+i,dcMap);
                if(i == 14){
                    i = 1;
                    ;
                    dataMap.put("countRoundMonth",roundCount);
                    dataMap.put("roundCountDay",AdscmBaseUtils.getInstance().sortMapByKeyNum(dayMap));
                    roundMap.put("round"+round,dataMap);
                    round++;
                    roundCount = 0;
                }else {
                    String theDate = dcMap.get("allDate").toString();
                    if (theDate.indexOf("12-31") > 4){
                        //证明是年的最后一天
                        dataMap.put("countRoundMonth",roundCount);
                        dataMap.put("roundCountDay",AdscmBaseUtils.getInstance().sortMapByKeyNum(dayMap));
                        roundMap.put("round"+round,dataMap);
                        round++;
                        roundCount = 0;
                    }
                    i++;
                }


            }

            map.put("allRoundData",AdscmBaseUtils.getInstance().sortMapByKeyNum(roundMap));
        }


        return map;
    }

    @Override
    public Map<String, Object> getPulpWeight(Integer year) throws AdscmSystemException {

        logger.info("查询浆量同期比，查询当前年、当前年的前一年、前两年、前两之前的总浆量及每个月的浆量比...");

        if (year != null && year >0){}else {
            year = AdscmDateUtils.getTheYear(new Date());
        }
//        String cacheDate = AdscmDateUtils.getNowOnlyDateFomat1(new Date());
//        Map<String, Object> cacheMap =pulpWeightMapCache.get(cacheDate);
//        if (cacheMap != null){
//            logger.info("返回缓存中数据...");
//            return cacheMap;
//        }
        Object result = objectRedisTemplate.opsForValue().get("xyDevelopAnalysisService.getPulpWeight");
        if (result != null){
            logger.info("从Redis中获取...");
            return (Map<String, Object>)result;
        }

        Map<String, Object> pulpWeightMap = new TreeMap<>();

        //查询今年、去年、前年每年的总献浆量
        String beginTime = (year - 2) + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        List<Map<String, Object>> countGroupByYear = xyDevelopAnalysisMapper.getCollCountGroupByYear(beginTime, endTime);
        Map<String, Object> collCountGroupByYear = this.getListMapToMap(countGroupByYear,"collYear","collCount");
        pulpWeightMap.put("collCountGroupByYear",collCountGroupByYear);

        //查询今年、去年、前年的每月的献浆总量
        String beginTime1 = (year - 3) + "-12-31";
        String endTime1 = year + "-12-31";
        List<Map<String, Object>> countGroupByMonth = xyDevelopAnalysisMapper.getCollCountGroupByMonth(beginTime1,endTime1,beginTime, endTime);
        Map<String, Object> collCountGroupByMonth = this.getListMapToMap(countGroupByMonth,"allDate","collCount");
        pulpWeightMap.put("collCountGroupByMonth",collCountGroupByMonth);

        //查询今年、去年、前年 ,每个月献浆的浆员，根据浆员的建档时间分类，分成：今年这个月建档的、去年这个月建档的、前年这个月建档的、前年之前这个月建档的
        List<Map<String, Object>> countGroupByMonthAndCreateYear = xyDevelopAnalysisMapper.getCollCountGroupByMonthAndCreateYear(beginTime1,endTime1,beginTime, endTime);

        List<Map<String, Object>> countMonthYear = new ArrayList<>();

        Map<String, List<Map<String, Object>>> tempMap = new TreeMap<>();//把所有数据，以年月为key，数据本身为value，存放在map中
        if(AdscmBaseUtils.getInstance().listIsNotEmpty(countGroupByMonthAndCreateYear)){
            for (Map<String, Object> cgmyMap : countGroupByMonthAndCreateYear) {
                String allDate = (String) cgmyMap.get("allDate");

                List<Map<String, Object>> tempList = tempMap.get(allDate);
                if (!AdscmBaseUtils.getInstance().listIsNotEmpty(tempList)){
                    tempList = new ArrayList<>();
                }
                tempList.add(cgmyMap);
                tempMap.put(allDate,tempList);
            }
        }

        //获取两个时间段之间的所有月份
        List<String> monthBetween = xyDevelopAnalysisMapper.getMonthBetween(beginTime1, endTime1);
        if (AdscmBaseUtils.getInstance().listIsNotEmpty(monthBetween)){

            int thisYear = year; //今年
            int lastYear = year - 1; //去年
            int lastYear2 = year - 2;//前年
            int lastYear3 = year - 3; //前年前

            boolean hasThisYearData = false;
            boolean hasLastYearData = false;
            boolean hasLastYear2Data = false;

            for (String yAndm : monthBetween) {
                List<Map<String, Object>> yAndmData = tempMap.get(yAndm);
                if (AdscmBaseUtils.getInstance().listIsNotEmpty(yAndmData)){

                    int lastYear3CollCount = 0;
                    for (Map<String, Object> ymd : yAndmData) {
//                        String allDate = (String) ymd.get("allDate");
                        String collCount = (String) ymd.get("collCount");
                        String createYear = (String) ymd.get("createYear");

                        int collCount_ = 0;
                        int createYear_ = 0;
                        try{
                            collCount_ = Integer.parseInt(collCount);
                        }catch (Exception e){}
                        try{
                            collCount_ = Integer.parseInt(createYear);
                        }catch (Exception e){}


                        if (createYear_ < lastYear2){
                            lastYear3CollCount += collCount_;
                        }else {
                            if(createYear_ == thisYear){
                                hasThisYearData = true;
                            }
                            if(createYear_ == lastYear){
                                hasLastYearData = true;
                            }
                            if(createYear_ == lastYear2){
                                hasLastYear2Data = true;
                            }
                            countMonthYear.add(ymd);
                        }

                    }
                    Map<String, Object> temp1 = this.loadMap(yAndm,lastYear3CollCount+"",lastYear3+"");
                    countMonthYear.add(temp1);

                    if (!hasThisYearData){
                        Map<String, Object> temp2 = this.loadMap(yAndm,"0",thisYear+"");
                        countMonthYear.add(temp2);
                    }
                    if (!hasLastYearData){
                        Map<String, Object> temp2 = this.loadMap(yAndm,"0",lastYear+"");
                        countMonthYear.add(temp2);
                    }
                    if (!hasLastYear2Data){
                        Map<String, Object> temp2 = this.loadMap(yAndm,"0",lastYear2+"");
                        countMonthYear.add(temp2);
                    }

                }else {
                    //没有找到这年这个月的数据
                    Map<String, Object> temp1 = this.loadMap(yAndm,"0",thisYear+"");
                    Map<String, Object> temp2 = this.loadMap(yAndm,"0",lastYear+"");
                    Map<String, Object> temp3 = this.loadMap(yAndm,"0",lastYear2+"");
                    Map<String, Object> temp4 = this.loadMap(yAndm,"0",lastYear3+"");

                    countMonthYear.add(temp1);
                    countMonthYear.add(temp2);
                    countMonthYear.add(temp3);
                    countMonthYear.add(temp4);
                }


            }
        }




//        if (countGroupByMonthAndCreateYear != null && countGroupByMonthAndCreateYear.size()>0){
//
//            int thisYear = year;
//            int lastYear = year - 1;
//            int lastYear2 = year - 2;
//            Map<String, String> tempMap = new HashMap<>();
//            for (Map<String, Object> cgmyMap : countGroupByMonthAndCreateYear) {
//                String allDate = (String) cgmyMap.get("allDate");
//                String collCount = (String) cgmyMap.get("collCount");
//                String createYear = (String) cgmyMap.get("createYear");
//
//                if (createYear != null &&  !"0".equals(createYear)){
//                    int cYear = 0;
//                    try{
//                        cYear = Integer.parseInt(createYear);
//                        if (cYear < lastYear2){
//                            //前年之前的
//                            cYear = lastYear2 - 1;
//
//                            String key = allDate+":"+cYear;
//                            String tempValue = tempMap.get(key);
//                            if(AdscmBaseUtils.getInstance().isNotEmpty(tempValue,null)){
//                                int lastCollCount = Integer.parseInt(tempValue);
//                                int thisCollCount = Integer.parseInt(collCount);
//                                tempMap.put(key,(lastCollCount + thisCollCount) + "");
//                            }else {
//                                tempMap.put(key,collCount);
//                            }
//                        }else{
//                            countMonthYear.add(cgmyMap);
//                        }
//
//                    }catch (Exception e){
//                        logger.error("",e);
//                    }
//
//                }else{
//                    //只要createYear为 0 ，那么 collCount 就一定为 0 ，反之同样成立 ，这个时候，一个月就只有一条数据
//                    //就需要手动构造几条每个月的每年的建档数据
//                    Map<String, Object> temp1 = this.loadMap(allDate,"0",thisYear+"");
//                    Map<String, Object> temp2 = this.loadMap(allDate,"0",lastYear+"");
//                    Map<String, Object> temp3 = this.loadMap(allDate,"0",lastYear2+"");
////                    Map<String, Object> temp4 = this.loadMap(allDate,"0",(lastYear2 - 1)+"");
//                    countMonthYear.add(temp1);
//                    countMonthYear.add(temp2);
//                    countMonthYear.add(temp3);
////                    countMonthYear.add(temp4);
//
//                }
//            }
//
//            List<String> monthBetween = xyDevelopAnalysisMapper.getMonthBetween(beginTime1, endTime1);
//            if (monthBetween != null && monthBetween.size()>0){
//                int theYear = year - 3;
//                for (String month : monthBetween) {
//                    String value = tempMap.get(month + ":" + theYear);
//                    Map<String, Object> temp = null;
//                    if(AdscmBaseUtils.getInstance().isNotEmpty(value,null)){
//                        temp = this.loadMap(month,value,theYear+"");
//                    }else {
//                        temp = this.loadMap(month,"0",theYear+"");
//                    }
//                    countMonthYear.add(temp);
//                }
//            }
//
//        }

        Collections.sort(countMonthYear, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                try{
                    String allDate1 = (String) o1.get("allDate");
                    String allDate2 = (String) o2.get("allDate");
                    if (allDate1.equals(allDate2)){
                        String crateYear1 = (String) o1.get("createYear");
                        String crateYear2 = (String) o2.get("createYear");
                        return crateYear1.compareTo(crateYear2);
                    }else {
                        return allDate1.compareTo(allDate2);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return 0;
                }

            }
        });

        pulpWeightMap.put("countMonthYear",countMonthYear);

        AdscmBaseUtils.getInstance().addObjToRedis("xyDevelopAnalysisService.getPulpWeight",pulpWeightMap,objectRedisTemplate,20, TimeUnit.HOURS);

        //把昨天的缓存清了
//        String cacheLastDate = AdscmDateUtils.getNowOnlyDateFomat2(new Date(),-1,Calendar.DATE);
//        cacheLastDate = AdscmDateUtils.getNowOnlyDateFomat1(AdscmDateUtils.parseDate(cacheLastDate));
//
//        Map<String, Object> lastCacheMap =pulpWeightMapCache.get(cacheLastDate);
//        if (lastCacheMap != null){
//            logger.info("清除昨天的缓存数据...");
//            pulpWeightMapCache.clear();
//        }
//        //把今天的缓存加进去
//        pulpWeightMapCache.put(AdscmDateUtils.getNowOnlyDateFomat1(new Date()),pulpWeightMap);

        return pulpWeightMap;
    }

    private Map<String, Object> loadMap(String allDate,String collCount,String createYear){
        Map<String, Object> temp = new HashMap<>();
        temp.put("allDate",allDate);
        temp.put("collCount",collCount);
        temp.put("createYear",createYear);
        return temp;
    }


    /**
     * 仅供本类使用，把list中的Map遍历，将map中的key和value取出来，把某个value作为新map的key，另外一个value作为新map的value，然后再把新map排序返回
     * @param mapList
     * @param key
     * @param value
     * @return
     */
    private Map<String, Object> getListMapToMap(List<Map<String, Object>> mapList,String key,String value) {

        Map<String, Object> resultMap = new HashMap<>();
        try{
            if (mapList != null && mapList.size()>0){
                for (Map<String, Object> map : mapList) {
                    String key1 = (String) map.get(key);
                    Object value1 = map.get(value);
                    resultMap.put(key1,value1);
                }
            }
            resultMap = AdscmBaseUtils.getInstance().sortMapByKey(resultMap);
        }catch (Exception e){
            logger.error("处理map异常",e);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getFrequencyCount(Integer year) throws AdscmSystemException {
        logger.info("查询返站浆员与返站浆员同期比，当年、去年、前年 三年的数据...");

        if (year != null && year >0){}else {
            year = AdscmDateUtils.getTheYear(new Date());
        }
        Object result = objectRedisTemplate.opsForValue().get("xyDevelopAnalysisService.getFrequencyCount");
        if (result != null){
            logger.info("从Redis中获取...");
            return (Map<String, Object>)result;
        }

        Map<String, Object> frequencyCount = new TreeMap<>();

        //查询每年每月的建档浆员的数量
//        String beginTime1 = (year - 3) + "-12-31";
//        String endTime1 = year + "-12-31";
//        String beginTime2 = (year - 2) + "-01-01 00:00:00";
//        String endTime2 = year + "-12-31 23:59:59";
//        List<Map<String, Object>> createCountByMonth = xyDevelopAnalysisMapper.getProviderCreateCountByMonth(beginTime1, endTime1, beginTime2, endTime2);
        Map<String, Object> createCountMap = this.getNewProGroupByMonth(year);
        frequencyCount.put("createCountMap",createCountMap);

        //查询前年每个月建档的浆员，在前年每个月的返站人数和每个月的浆量
        String beginTime1 = (year - 3) + "-12-31";
        String endTime1 = (year - 2)  + "-12-31";
        String endTime3 = (year - 2) + "-12-31 23:59:59";
        Map<String, Object> lastLastYearFrequency = this.queryAllMonthFrequency(beginTime1, endTime1,endTime3,year - 2);
        frequencyCount.put("lastLastYearFrequency",lastLastYearFrequency);

        //去年
        beginTime1 = (year - 2) + "-12-31";
        endTime1 = (year - 1)  + "-12-31";
        endTime3 = (year - 1) + "-12-31 23:59:59";
        Map<String, Object> lastYearFrequency = this.queryAllMonthFrequency(beginTime1, endTime1,endTime3,year - 1);
        frequencyCount.put("lastYearFrequency",lastYearFrequency);

        //今年
        beginTime1 = (year - 1) + "-12-31";
        endTime1 = year  + "-12-31";
        endTime3 = year + "-12-31 23:59:59";
        Map<String, Object> currentYearFrequency = this.queryAllMonthFrequency(beginTime1, endTime1,endTime3,year);
        frequencyCount.put("currentYearFrequency",currentYearFrequency);

//        objectRedisTemplate.opsForValue().get("xyDevelopAnalysisService.getFrequencyCount",frequencyCount.);
        AdscmBaseUtils.getInstance().addObjToRedis("xyDevelopAnalysisService.getFrequencyCount",frequencyCount,objectRedisTemplate,20, TimeUnit.HOURS);

        return frequencyCount;
    }

    private Map<String, Object> queryAllMonthFrequency(String beginTime1,String endTime1,String endTime3,int year){
        Map<String, Object> frequencyCountYearsMonth = new HashMap<>();

        try {
            final List<String> successList = new ArrayList<>();
            for(int i = 1;i<13;i++){
                String month = "";
                if( i < 10){
                    month = "0" + i;
                }else {
                    month = "" + i;
                }

//                final String fMonth = month;

                String beginTime2 = year + "-"+month+"-01 00:00:00";
                Date tempD = AdscmDateUtils.parseDate(beginTime2);
                String endTime2 = AdscmDateUtils.getNowOnlyDateFomat1(AdscmDateUtils.getLastDayOfTheMonth(tempD)) + " 23:59:59";

                List<Map<String, Object>> list = xyDevelopAnalysisMapper.getFrequencyCountYearsMonth(beginTime1, endTime1, beginTime2, endTime2,endTime3);

                frequencyCountYearsMonth.put(year + "-" + month,list);

                successList.add(year + "-" + month);

            }


        }catch (Exception e){
            logger.error("",e);
        }

        return AdscmBaseUtils.getInstance().sortMapByKeyNum(frequencyCountYearsMonth);

    }


    @Override
    public Map<String, Object> getNewAndOutProviderCount(Integer year) throws AdscmSystemException {

        logger.info("查询新浆员同期比，当年、去年、前年 三年的数据...");

        if (year != null && year >0){}else {
            year = AdscmDateUtils.getTheYear(new Date());
        }
        Object result = objectRedisTemplate.opsForValue().get("xyDevelopAnalysisService.getNewAndOutProviderCount");
        if (result != null){
            logger.info("从Redis中获取...");
            return (Map<String, Object>)result;
        }

        Map<String, Object> newAndOutProviderMap = new TreeMap<>();

        //查询三年的每年的建档总人数
        String beginTime = (year - 2) + "-01-01 00:00:00";
        String endTime = year  + "-12-31 23:59:59";
        List<Map<String, Object>> createCountYearList = xyDevelopAnalysisMapper.getCreateCountYear(beginTime, endTime);
        Map<String, Object> createCountYear = this.getListMapToMap(createCountYearList,"createYear","createCount");
        newAndOutProviderMap.put("createCountYear",createCountYear);

        //查询三年的每个月的建档人数
        Map<String, Object> createCountMonth = this.getNewProGroupByMonth(year);
        newAndOutProviderMap.put("createCountMonth",createCountMonth);

        //查询三年每年的R浆员总人数
        List<Map<String, Object>> createRCountYearList = xyDevelopAnalysisMapper.getCreateRCountYear(beginTime, endTime);
        Map<String, Object> createRCountYear = this.getListMapToMap(createRCountYearList,"createYear","createCount");
        newAndOutProviderMap.put("createRCountYear",createRCountYear);

        //查询三年的每个月的 R 浆员人数
        String beginTime1 = (year - 3) + "-12-31";
        List<Map<String, Object>> createRCountMonthList = xyDevelopAnalysisMapper.getCreateRCountMonth(beginTime1,beginTime, endTime);
        Map<String, Object> createRCountMonth = this.getListMapToMap(createRCountMonthList,"createMonth","createCount");
        newAndOutProviderMap.put("createRCountMonth",createRCountMonth);

        //查询三年每年的只建了档，但未献浆（也不是R浆员）浆员总人数
        List<Map<String, Object>> createNotComeCountYearList = xyDevelopAnalysisMapper.getCreateNotComeCountYear(beginTime, endTime);
        Map<String, Object> createNotComeCountYear = this.getListMapToMap(createNotComeCountYearList,"createYear","notComeCount");
        newAndOutProviderMap.put("createNotComeCountYear",createNotComeCountYear);


        //查询三年的每个月的只建了档，但未献浆（也不是R浆员）浆员总人数
        List<Map<String, Object>> createNotComeCountMonthList = xyDevelopAnalysisMapper.getCreateNotComeCountMonth(beginTime1,beginTime, endTime);
        Map<String, Object> createNotComeCountMonth = this.getListMapToMap(createNotComeCountMonthList,"createMonth","notComeCount");
        newAndOutProviderMap.put("createNotComeCountMonth",createNotComeCountMonth);


        //查询三年每年的淘汰浆员总人数（超龄）
        beginTime1 = (year - 2 - 56) + "-01-01";
        String endTime1 = (year - 56) + "-12-31";
        List<Map<String, Object>> outProviderCountYearList = xyDevelopAnalysisMapper.getOutProviderCountYear(beginTime1,endTime1,beginTime, endTime);
        Map<String, Object> outProviderCountYear = this.getListMapToMap(outProviderCountYearList,"outYear","outProviderCount");
        newAndOutProviderMap.put("outProviderCountYear",outProviderCountYear);

        //查询三年每个月的淘汰浆员总人数（超龄）
        beginTime = (year - 3) + "-12-31";
        endTime = year + "-12-31";
        List<Map<String, Object>> outProviderCountMonthList = xyDevelopAnalysisMapper.getOutProviderCountMonth(beginTime1,endTime1,beginTime, endTime);
        Map<String, Object> outProviderCountMonth = this.getListMapToMap(outProviderCountMonthList,"outMonth","outProviderCount");
        newAndOutProviderMap.put("outProviderCountMonth",outProviderCountMonth);

        //三年每年的浆员净增长数（每年的新浆员总数 - 每年的淘汰浆员总数）
        Map<String, Object> netBoostCountYear = new HashMap<>();
        for(int i = (year-2);i<= year;i++){
            try{
                String increase = (String)createCountYear.get(i+"");//增加
                String reduce = (String)outProviderCountYear.get(i+"");//减少
                int netBoost = Integer.parseInt(increase) - Integer.parseInt(reduce);//净增长
                netBoostCountYear.put(i+"",netBoost+"");
            }catch (Exception e){
                logger.error("",e);
            }
        }
        newAndOutProviderMap.put("netBoostCountYear",netBoostCountYear);


        //三年每个月的浆员净增长数（每个月的新浆员总数 - 每个月的淘汰浆员总数）
        Map<String, Object> netBoostCountMonth = new HashMap<>();
        for(int i = (year-2);i<= year;i++){
            for(int j = 1;j<13;j++){
                String month = null;
                if (j<10){
                    month = "0"+j;
                }else {
                    month = ""+j;
                }
                try{
                    String increase = (String)createCountMonth.get(i+"-"+month);//增加
                    String reduce = (String)outProviderCountMonth.get(i+"-"+month);//减少
                    int netBoost = Integer.parseInt(increase) - Integer.parseInt(reduce);//净增长
                    netBoostCountMonth.put(i+"-"+month,netBoost+"");
                }catch (Exception e){
                    logger.error("",e);
                }

            }
        }
        newAndOutProviderMap.put("netBoostCountMonth",netBoostCountMonth);


        AdscmBaseUtils.getInstance().addObjToRedis("xyDevelopAnalysisService.getNewAndOutProviderCount",newAndOutProviderMap,objectRedisTemplate,20, TimeUnit.HOURS);
        return newAndOutProviderMap;

    }


    private Map<String, Object> getNewProGroupByMonth(int year){
        //查询每年每月的建档浆员的数量
        String beginTime1 = (year - 3) + "-12-31";
        String endTime1 = year + "-12-31";
        String beginTime2 = (year - 2) + "-01-01 00:00:00";
        String endTime2 = year + "-12-31 23:59:59";
        List<Map<String, Object>> createCountByMonth = xyDevelopAnalysisMapper.getProviderCreateCountByMonth(beginTime1, endTime1, beginTime2, endTime2);
        Map<String, Object> createCountMap = this.getListMapToMap(createCountByMonth,"createMonth","createCount");
        return createCountMap;
    }

    @Override
    public AdscmPage<LinkAnalysisProviderSupport> getThisYearComedNotLink(Integer current, Integer size) throws AdscmSystemException {
        logger.info("查看今年已献浆未链接浆员...");

        current = AdscmBaseUtils.getInstance().getCurrentStartIdx(current,size);

        AdscmPage<LinkAnalysisProviderSupport> page = new AdscmPage<>(current,size);
        Map<String,Object> condition = new HashMap<>();

        int year = AdscmDateUtils.getTheYear(new Date());
        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        condition.put("beginTime",beginTime);
        condition.put("endTime",endTime);
        page.setCondition(condition);

        List<LinkAnalysisProviderSupport> list = null;
        Integer total = xyDevelopAnalysisMapper.getThisYearComedNotLinkCount(page);
        if (total == null){
            total = 0;
            list = new ArrayList<>();
            page.setRecords(list);
        }else {
            list = xyDevelopAnalysisMapper.getThisYearComedNotLinkPage(page);
            page.setRecords(list);
//            this.loadLastThisYearCollCount_1(list,year,beginTime,endTime);
            this.loadLastThisYearCollCount_2(page,year);
        }
        page.setTotal(total);

        return page;
    }

    /**
     * 构造浆员去年、今年和总的浆量（方式1，查询慢）
     * @param list
     * @param year
     * @param beginTime
     * @param endTime
     */
    private void loadLastThisYearCollCount_1(List<LinkAnalysisProviderSupport> list,int year,String beginTime,String endTime) {
        if (list != null && list.size() > 0) {

            String lastBeginTime = (year - 1) + "-01-01 00:00:00";
            String lastEndTime = (year - 1) + "-12-31 23:59:59";


            for (LinkAnalysisProviderSupport linkProvider : list) {
                Wrapper<ProviderCollection> wrapper = new EntityWrapper<>();
                //总献浆量
                wrapper.eq("providerNo", linkProvider.getProviderId());
                wrapper.eq("isDeal", 1);
                wrapper.ge("totalPlasmaNum", 590);
                int totalCollCount = providerCollectionMapper.selectCount(wrapper);

                Wrapper<ProviderCollection> thisYearWrapper = wrapper.clone();

                // 去年献浆量
                wrapper.between("collectionDate", lastBeginTime, lastEndTime);
                int lastYearCollCount = providerCollectionMapper.selectCount(wrapper);

                //今年献浆量
                thisYearWrapper.between("collectionDate", beginTime, endTime);
                int thisYearCollCount = providerCollectionMapper.selectCount(thisYearWrapper);

                linkProvider.setTotalCollCount(totalCollCount);
                linkProvider.setLastYearCollCount(lastYearCollCount);
                linkProvider.setThisYearCollCount(thisYearCollCount);
            }
        }
    }

    /**
     * 构造浆员去年、今年和总的浆量(方式2)
     * @param page
     */
    private void loadLastThisYearCollCount_2(AdscmPage<LinkAnalysisProviderSupport> page,int year){
        if (page.getRecords() != null && page.getRecords().size()>0){

            String lastBeginTime = (year - 1) + "-01-01 00:00:00";
            String lastEndTime = (year - 1) + "-12-31 23:59:59";

            page.getCondition().put("lastBeginTime",lastBeginTime);
            page.getCondition().put("lastEndTime",lastEndTime);

            List<LinkAnalysisProviderSupport> countList = xyDevelopAnalysisMapper.getProviderCollCount(page);

            Map<Long,LinkAnalysisProviderSupport> temp = new HashMap<>();
            if(AdscmBaseUtils.getInstance().listIsNotEmpty(countList)){
                for (LinkAnalysisProviderSupport linkProvider : countList) {
                    temp.put(linkProvider.getProviderId(),linkProvider);
                }
            }

            if(AdscmBaseUtils.getInstance().listIsNotEmpty(page.getRecords())){
                for (LinkAnalysisProviderSupport record : page.getRecords()) {
                    LinkAnalysisProviderSupport count = temp.get(record.getProviderId());
                    if (count != null){
                        record.setTotalCollCount(count.getTotalCollCount());
                        record.setLastYearCollCount(count.getLastYearCollCount());
                        record.setThisYearCollCount(count.getThisYearCollCount());
                    }else{
                        record.setTotalCollCount(0);
                        record.setLastYearCollCount(0);
                        record.setThisYearCollCount(0);
                    }
                }
            }


        }
    }


    @Override
    public AdscmPage<LinkAnalysisProviderSupport> getLinkedThisYearNotComed(Integer current, Integer size) throws AdscmSystemException {

        logger.info("查看已链接今年未献浆浆员...");

        current = AdscmBaseUtils.getInstance().getCurrentStartIdx(current,size);

        AdscmPage<LinkAnalysisProviderSupport> page = new AdscmPage<>(current,size);
        Map<String,Object> condition = new HashMap<>();

        int year = AdscmDateUtils.getTheYear(new Date());
        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        condition.put("beginTime",beginTime);
        condition.put("endTime",endTime);
        page.setCondition(condition);

        List<LinkAnalysisProviderSupport> list = null;
        Integer total = xyDevelopAnalysisMapper.getLinkedThisYearNotComedCount(page);
        if (total == null){
            total = 0;
            list = new ArrayList<>();
            page.setRecords(list);
        }else {
            list = xyDevelopAnalysisMapper.getLinkedThisYearNotComedPage(page);
            page.setRecords(list);
//            this.loadLastThisYearCollCount_1(list,year,beginTime,endTime);
            this.loadLastThisYearCollCount_2(page,year);

            //查看这些人去年同期的浆量
            condition = new HashMap<>();
            beginTime = (year - 1) + "-01-01 00:00:00";
            endTime = AdscmDateUtils.getNowOnlyDateFomat1(new Date(),-1) + " 23:59:59";
            condition.put("beginTime",beginTime);
            condition.put("endTime",endTime);
            page.setCondition(condition);
            List<LinkAnalysisProviderSupport> tempCount = xyDevelopAnalysisMapper.getProviderCollCountByTimes(page);

            Map<Long,LinkAnalysisProviderSupport> temp = new HashMap<>();
            if(AdscmBaseUtils.getInstance().listIsNotEmpty(tempCount)){
                for (LinkAnalysisProviderSupport linkProvider : tempCount) {
                    temp.put(linkProvider.getProviderId(),linkProvider);
                }
            }

            if(AdscmBaseUtils.getInstance().listIsNotEmpty(page.getRecords())){
                for (LinkAnalysisProviderSupport record : page.getRecords()) {
                    LinkAnalysisProviderSupport count = temp.get(record.getProviderId());
                    if (count != null){
                        record.setLastYearThisTimeCollCount(count.getLastYearThisTimeCollCount());
                    }else {
                        record.setLastYearThisTimeCollCount(0);
                    }
                }
            }

        }
        page.setTotal(total);


        return page;
    }


    @Override
    public List<Map<String, Object>> getLinkNursePCount() throws AdscmSystemException {
        logger.info("查看所有链接护士对应的链接浆员数量");

        return  xyLinkMapper.getLinkNursePCount();
    }
}
